import {CheckOutlined, InboxOutlined, UndoOutlined} from '@ant-design/icons';
import {
  Layout,
  message,
  Form,
  DatePicker,
  Upload,
  UploadProps,
  Space,
  Col,
  Input,
  Popconfirm,
  Select,
  Modal, Button,
} from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';

import '@/assets/css/index.less';
import ProForm, { ProFormText, ProFormSelect } from '@ant-design/pro-form';
import { useForm } from 'antd/es/form/Form';
import { getPhotoCategoryList, releasePhoto, uploadList } from '@/services/pictureManager';
import axios from 'axios';
import formatDate from '@/utils/formatDate';
import { useLocation } from 'umi';
import { VideoPlayer } from '@/utils/videoPlayer';
import { insertVideo } from '@/services/videoManager';
const { Header } = Layout;

const { TextArea } = Input;
import {BASE_URL} from "../../../../proxyConfig";

const MNTPrefix = BASE_URL;

const VideoDetail: React.FC = () => {
  const playerRef = React.useRef(null);

  const location = useLocation();
  const [currentFormValues, setCurrentFormValues] = useState(location.state?.videoForm);
  console.log('video publish:-----', currentFormValues);

  const [videoData, setVideoData] = useState([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const handlePreview = async (file: UploadFile) => {
    setPreviewImage(file.url);
    setPreviewOpen(true);
    setPreviewTitle(file.title);
  };
  const handleCancel = () => setPreviewOpen(false);
  const handleImageChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>
    setFileList(newFileList);
  const onSubmit = async (values) => {
    window.history.back();
  };
  const props: UploadProps = {
    name: 'file',
    multiple: true,
    onChange(info) {},
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },

    async customRequest(param) {
      const { onSuccess, onError, file, onProgress } = param;
      const config = {
        headers: { 'content-type': 'multipart/form-data' },
        onUploadProgress: (event) => {
          console.log(event.loaded, event.total);

          const percent = Math.floor((event.loaded / event.total) * 100);
          setProgress(percent);
          if (percent === 100) {
            setTimeout(() => setProgress(0), 1000);
          }
          onProgress({ percent: (event.loaded / event.total) * 100 });
        },
      };
      let formData = new FormData();
      formData.append('file', file);
      try {
        const response = await axios.post('/api/v1/video/formUpload', formData, config);
        videoData.push(response.data.data);
        setVideoData(videoData);
        onSuccess(response);
      } catch (error) {
        message.error(error.response.data.data);
        onError({ error });
      }
    },
  };
  const [form] = useForm();
  const formLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 14,
    },
  };

  const getVideoDetail = () => {};

  const handlePlayerReady = (player) => {
    playerRef.current = player;

    // you can handle player events here
    player.on('waiting', () => {
      console.log('player is waiting');
    });

    player.on('dispose', () => {
      console.log('player will dispose');
    });
  };
  return (
    <PageContainer
      header={{
        title: '视频详情',
        breadcrumb: {
          items: [
            {
              // path: '',
              title: '视频管理',
            },
            {
              title: '视频详情',
            },
          ],
        },
      }}
    >
      <ProForm
        form={form}
        layout="horizontal"
        {...formLayout}
        initialValues={currentFormValues || {}}
        onFinish={onSubmit}
        // onReset={onReset}
        submitter={{
          render: (_, dom) => (
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Space>
                {/*{dom}*/}
                {<Button onClick={() => {
                  _.reset()
                }}><UndoOutlined />重置</Button>}
                {<Button type={"primary"} onClick={() => {
                  _.submit()
                }}><CheckOutlined />返回</Button>}

              </Space>
            </div>
          ),
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '主题名称必填',
            },
          ]}
          width="md"
          name="title"
          placeholder="请填写主题名称"
          disabled={true}
          label="主题"
        />
        <Form.Item label="描述" name="description">
          <TextArea
            disabled={true}
            className=""
            showCount
            maxLength={300}
            // style={{ height: 120, marginBottom: 24, width: 300}}
            // onChange={onChange}
            placeholder="输入备注信息"
          />
        </Form.Item>

        {/* <Form.Item  label="发布时间" name= "releaseTime">
                <DatePicker format={"YYYY-MM-DD"}/>
            </Form.Item> */}
        <Form.Item label="封面图片" name="coverImage">
          <Upload
            {...props}
            action="/api/v1/photo/uploadList"
            listType="picture-card"
            fileList={[
              { ...JSON.parse(JSON.stringify(currentFormValues).replace('coverImage', 'url')) },
            ]}
            headers={{'Token':'Bearer ' + +window.sessionStorage.getItem('userToken')}}
            onPreview={handlePreview}
            onChange={handleImageChange}
          >
            {/* {fileList.length >= 2 ? null : "+ 上传封面"} */}
          </Upload>
        </Form.Item>
        <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={currentFormValues.coverImage} />
        </Modal>
        <Form.Item label="视频" name="fileList">
          {/* <VideoPlayer
                    options={videoOptions}
                    onReady={handlePlayerReady}
                >

                </VideoPlayer> */}
          <video width="320" height="240" controls>
            <source src={currentFormValues.httpurl} type="video/mp4" />
            {/* <source src="movie.ogg" type="video/ogg"/> */}
          </video>
        </Form.Item>
      </ProForm>
    </PageContainer>
  );
};
export default VideoDetail;
